<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="批次编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入批次编号"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="序号" type="index" />
      <el-table-column label="批次编号" align="center" prop="code" />
      <el-table-column label="数量" align="center" prop="snNum" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="有效期至"
        align="center"
        prop="expireTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expireTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已使用数量（个）" align="center" prop="snUsedNum">
        <template slot-scope="scope">
          <span style="color: #1890ff; cursor: pointer;" @click="handleSN(scope.row,'used')">{{ scope.row.snUsedNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="未使用数量（个）" align="center" prop="snUnUsedNum">
      <template slot-scope="scope">
          <span style="color: #1890ff; cursor: pointer;" @click="handleSN(scope.row)">{{ scope.row.snUnUsedNum }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:tenant:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:tenant:delete']">删除</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="checkSpecimen(scope.row)"
            >查看样本</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- Discard 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="800px">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        size="medium"
        label-width="100px"
      >
        <el-col :span="24">
          <el-form-item label="渠道名称" prop="tenantId">
            <el-select
              v-model="form.tenantId"
              placeholder="请选择渠道名称"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in tenantIdOptions"
                :key="index"
                :label="item.name"
                :value="item.id"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactName">
            <el-input
              v-model="form.contactName"
              placeholder="请输入联系人"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactMobile">
            <el-input
              v-model="form.contactMobile"
              placeholder="请输入联系电话"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="所属项目" prop="projectId">
            <el-select
              v-model="form.projectId"
              @change="changeProject"
              placeholder="请选择所属项目"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in projectIdOptions"
                :key="index"
                :label="item.name"
                :value="item.id"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="discount" label="单价（元）" prop="price">
            <el-input
              v-show="!form.isDiscount"
              v-model="form.price"
              placeholder="请输入单价（元）"
              clearable
              :disabled="true"
              :style="{ width: '80%' }"
            >
            </el-input>
            <el-input
              v-show="form.isDiscount"
              v-model="form.discountPrice"
              placeholder="请输入单价（元）"
              clearable
              :disabled="true"
              :style="{ width: '80%' }"
            >
            </el-input>
            <el-button
              type="success"
              @click="changeDiscount"
              :disabled="form.isDiscount"
              size="mini"
              round
              >折扣</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单数量（个）" prop="snNum">
            <el-input
              v-model="form.snNum"
              placeholder="请输入订单数量（个）"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="总金额（元）" prop="totalPrice">
            <el-input
              v-model="form.totalPrice"
              placeholder="请输入总金额（元）"
              :disabled="true"
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="付款方式" prop="payType">
            <el-select
              v-model="form.payType"
              placeholder="请选择付款方式"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in payTypeOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="快递单号" prop="expressNo">
            <el-input
              v-model="form.expressNo"
              placeholder="请输入快递单号"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="订单状态" prop="status">
            <el-select
              v-model="form.status"
              placeholder="请选择订单状态"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in testTypeDictData"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- SN已使用&未使用对话框(添加 / 修改) -->
    <el-dialog :title="titleSN" :visible.sync="openSN" width="800px">
      <el-form
        ref="formData"
        :model="formData"
        :rules="formRules"
        size="medium"
        label-width="150px"
      >
        <el-col :span="24">
          <el-form-item label="产品批次" prop="code">
            <el-input
              v-model="formData.code"
              placeholder=""
              :disabled="true"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品数量" prop="snNum">
            <el-input
              v-model="formData.snNum"
              placeholder=""
              :disabled="true"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="有效期至" prop="expireTime">
            <el-date-picker
              v-model="formData.expireTime"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :style="{ width: '100%' }"
              placeholder="请选择有效期至"
              clearable
              :disabled="true"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24"></el-col>
      </el-form>
      <br />
      <!-- 显示已使用SN -->
      <div v-if="activeName">
        <Used :code="snCode" />
      </div>
      <!-- 显示未使用SN -->
      <div v-else>
        <Unused :code="snCode" />
      </div>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitSNForm">确 定</el-button> -->
        <el-button @click="close">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTenantList as getProjectList,
  getTenant as getProjectInfo,
} from "@/api/items/index";
import {
  getTenantPage,
} from "@/api/sn/index";
import { listSimpleMenus } from "@/api/system/menu";
import Used from './components/used.vue'
import Unused from './components/unused.vue'

export default {
  name: "TenantPackage",
  components: { Used, Unused },
  data() {
    return {
      snCode: '',
      usedList: [],
      unusedList: [],
      activeName: "bind",
      // 日期范围
      dateRange: [],
      testTypeDictData: [
        { label: "未发货", value: "to_deliver" },
        { label: "已发货", value: "delivered" },
      ],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 租户套餐列表
      list: [],
      // 弹出层标题
      title: "",
      titleSN: "",
      // 是否显示弹出层
      open: false,
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        tenantName: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      formData: {},
      menuExpand: false,
      menuNodeAll: false,
      menuCheckStrictly: true,
      defaultProps: {
        label: "name",
        children: "children",
      },
      menuOptions: [], // 菜单列表
      // 表单校验
      rules: {
        tenantId: [
          {
            required: true,
            message: "请选择渠道名称",
            trigger: "change",
          },
        ],
        contactName: [
          {
            required: true,
            message: "请输入联系人",
            trigger: "blur",
          },
        ],
        contactMobile: [
          {
            required: true,
            message: "请输入联系电话",
            trigger: "blur",
          },
          {
            pattern:
              /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
            message: "支持11位手机号码",
            trigger: "blur",
          },
        ],
        projectId: [
          {
            required: true,
            message: "请选择所属项目",
            trigger: "change",
          },
        ],
        price: [
          {
            required: true,
            message: "请输入单价（元）",
            trigger: "blur",
          },
        ],
        discountPrice: [
          {
            required: true,
            message: "请输入单价（元）",
            trigger: "blur",
          },
        ],
        snNum: [
          {
            required: true,
            message: "请输入订单数量（个）",
            trigger: "blur",
          },
        ],
        totalPrice: [
          {
            required: true,
            message: "请输入总金额（元）",
            trigger: "blur",
          },
        ],
        payType: [
          {
            required: true,
            message: "请选择付款方式",
            trigger: "change",
          },
        ],
        status: [
          {
            required: true,
            message: "请选择订单状态",
            trigger: "change",
          },
        ],
        expressNo: [],
      },
      formRules: {
        snNum: [
          {
            required: true,
            message: "",
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "请输入订单号",
            trigger: "blur",
          },
        ],
        projectId: [
          {
            required: true,
            message: "请选择所属项目",
            trigger: "change",
          },
        ],
        snBatchCode: [
          {
            required: true,
            message: "请选择产品批次",
            trigger: "change",
          },
        ],
        snCodes: [
          {
            required: true,
            message: "请输入SN码",
            trigger: "blur",
          },
        ],
        expireTime: [
          {
            required: true,
            message: "请选择有效期至",
            trigger: "change",
          },
        ],
      },
      payTypeOptions: [
        {
          label: "货到付款",
          value: "delivery",
        },
        {
          label: "月结",
          value: "monthly",
        },
      ],
      projectIdOptions: [],
      tenantIdOptions: [],
      discountPrice: "",
      //SN
      openSN: false,
      snBatchCodeOptions: [],
    };
  },
  watch: {
    "form.snNum": function (val) {
      if (this.form.isDiscount) {
        this.form.totalPrice =
          (val && parseFloat(this.form.discountPrice * val).toFixed(2)) || 0;
      } else {
        this.form.totalPrice =
          (val && parseFloat(this.form.price * val).toFixed(2)) || 0;
      }
    },
  },
  created() {
    this.getList();
    this.getMenus();
    this.getProject();
    this.getTenant();
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },
    changeBatch() {
      this.formData.snCodes = "";
      this.formData.expireTime = undefined
      this.setExpireTime();
    },
    //根据产品批次获取对应的过期时间
    setExpireTime() {
      const temp = this.snBatchCodeOptions.filter(
        (item) => item.code == this.formData.snBatchCode
      );
      const time = temp.length && temp[0].expireTime;
      if (time) {
        this.formData.expireTime = this.parseTime(time);
      }
    },
    getSNList(code) {
      getSN({ orderId: code }).then((response) => {
        this.snBatchCodeOptions = response.data || [];
      });
    },
    changeDiscount() {
      this.form.price = this.discountPrice;
    },
    changeProject() {
      getProjectInfo(this.form.projectId).then((response) => {
        const { price, discountPrice } = response.data;
        this.form.price = price;
        this.discountPrice = discountPrice;
      });
    },
    getTenant() {
      getTenantList({
        type: "agent",
        status: 0,
      }).then((response) => {
        this.tenantIdOptions = response.data || [];
      });
    },
    getProject() {
      getProjectList().then((response) => {
        this.projectIdOptions = response.data || [];
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = { ...this.queryParams, };
      // this.addDateRange(this.queryParams, [
      //   this.dateRange[0] ? this.dateRange[0] + ' 00:00:00' : undefined,
      //   this.dateRange[1] ? this.dateRange[1] + ' 23:59:59' : undefined,
      // ])
      // 执行查询
      getTenantPage(params).then((response) => {
        this.list = response.data.list || [];
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    close() {
      this.openSN = false;
      this.resetSN();
    },
    /** 表单重置 */
    reset() {
      // 表单重置
      this.form = {
        id: undefined,
        tenantId: undefined,
        contactName: undefined,
        contactMobile: undefined,
        projectId: undefined,
        price: undefined,
        snNum: undefined,
        totalPrice: undefined,
        payType: undefined,
        expressNo: undefined,
        status: undefined,
      };
      this.resetForm("form");
    },
    resetSN() {
      // 表单重置
      this.formData = {
        code: undefined,
        snSum: undefined,
        expireTime: undefined,
      };
      this.resetForm("formData");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      // 表单重置
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
      // 设置为非严格，继续使用半选中
      this.menuCheckStrictly = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      this.open = true;
      this.title = "编辑";
      // 获得菜单列表
      // getTenant(id).then((response) => {
      //   this.form = response.data;
      //   const { discountPrice } = response.data;
      //   this.discountPrice = discountPrice;
      // });
    },
    /** SN操作 */
    handleSN(row, used) {
      this.resetSN();
      // const id = row.id;
      this.openSN = true;
      this.activeName = used;
      Object.assign(this.formData, row)
      const { expireTime, code, snUsedNum, snUnUsedNum } = row
      this.formData.expireTime = this.parseTime(expireTime)
      this.snCode = code
      if(used){
        //已使用SN
        this.titleSN = `已使用SN（${snUsedNum}个）`;
      }else{
        //未使用SN
        this.titleSN = `未使用SN（${snUnUsedNum}个）`;
      }
      
      
    },
    /** 查看样本 */
    checkSpecimen(row) {
      const { tenantName } = row
      this.$router.push({path: '/specimen', query: { tenantName: tenantName}})
    },
    /** 获得菜单 */
    getMenus() {
      listSimpleMenus().then((response) => {
        // 处理 menuOptions 参数
        this.menuOptions = [];
        // 只需要配置
        this.menuOptions.push(...this.handleTree(response.data, "id"));
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        // 修改的提交
        this.form.discountPrice = this.form.price;
        if (this.form.id != null) {
          updateTenant({
            ...this.form,
            // menuIds: [...this.$refs.menu.getCheckedKeys(), ...this.$refs.menu.getHalfCheckedKeys()]
          }).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createTenant({
          ...this.form,
          // menuIds: [...this.$refs.menu.getCheckedKeys(), ...this.$refs.menu.getHalfCheckedKeys()]
        }).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 提交按钮 */
    submitSNForm() {
      this.$refs["formData"].validate((valid) => {
        if (!valid) {
          return;
        }
        //格式化snCodes
        let snCodes = [];
        const trimArr = this.formData.snCodes;
        if (trimArr.indexOf(",") > -1) {
          snCodes = trimArr.split(",").filter(Boolean);
        } else {
          snCodes = [this.formData.snCodes];
        }
        // 修改的提交
        if (this.activeName == "bind") {
          bindSN({
            orderId: this.formData.id,
            snBatchCode: this.formData.snBatchCode,
            snCodes: snCodes,
          }).then((response) => {
            this.$modal.msgSuccess("绑定成功");
            this.openSN = false;
            this.getList();
          });
          return;
        }
        // 解绑的提交
        unbindSN({
          orderId: this.formData.id,
          snBatchCode: this.formData.snBatchCode,
          snCodes: snCodes,
        }).then((response) => {
          this.$modal.msgSuccess("解绑成功");
          this.openSN = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm('是否确认删除编号为"' + id + '"的数据项?')
        .then(function () {
          return deleteTenant(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      let treeList = this.menuOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value) {
      this.form.menuCheckStrictly = value;
    },
  },
};
</script>
<style scoped>
.discount {
  position: relative;
}
.discount .el-button {
  position: absolute;
  top: 4px;
  right: -16px;
}
</style>
